home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / cpp_libs / brent_cc.lha / brent_cc / vzeroin.cc < prev    next >
C/C++ Source or Header  |  1993-08-08  |  1KB  |  54 lines

  1. // This may look like C code, but it is really -*- C++ -*-
  2. //
  3. //            Verify ZEROIN routine
  4.  
  5. #include "math_num.h"
  6. #include <ostream.h>
  7.  
  8. static int counter;            // Iteration counter
  9.  
  10.             // Run a test
  11. static void test
  12.   (const double a, const double b, double (*f)(double x), const char *msg)
  13. {
  14.   double root;
  15.   counter = 0;
  16.   cout << form("\nFor function %s,\nthe root over [%g,%g] is\t%.9e\n",msg,a,b,
  17.      (root=zeroin(a,b,f)) );
  18.   cout << form("Function value at the root found\t%.4e\n"
  19.            "No. of iterations\t\t%d\n",
  20.            (*f)(root), counter);
  21. }
  22.  
  23. double f1(const double x)        // Test from the Forsythe book
  24. {
  25.   counter++;
  26.   return (sqr(x)-2)*x - 5;
  27. }
  28.  
  29. double f2(const double x)
  30. {
  31.   counter++;
  32.   return cos(x) - x;
  33. }
  34.  
  35. double f3(const double x)
  36. {
  37.   counter++;
  38.   return sin(x) - x;
  39. }
  40.  
  41.  
  42. main()
  43. {
  44.   cout << "\n\n" << _Minuses <<
  45.           "\n\t\tTesting the Brent's root finder\n\n";
  46.  
  47.   test(2.0,3.0,f1,"x^3 - 2*x - 5");
  48.   cout << "Exact root is \t\t2.0945514815\n";
  49.  
  50.   test(2.0,3.0,f2,"cos(x)-x");
  51.   test(-1.0,3.0,f2,"cos(x)-x");
  52.   test(-1.0,3.0,f3,"sin(x)-x");
  53. }
  54.